package com.example.accountingapp;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class RecordTimeActivity extends AppCompatActivity {

    private TextView tvRecords;
    private Button btnClearRecords;
    private DatabaseHelperIncome dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_record_time);

        tvRecords = findViewById(R.id.tvRecords);
        btnClearRecords = findViewById(R.id.btnClearRecords);
        dbHelper = new DatabaseHelperIncome(this);

        showRecords();

        btnClearRecords.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearRecords();
            }
        });
    }

    private void showRecords() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();

        String[] projection = {
                DatabaseContractIncome.IncomeEntry.COLUMN_INCOME,
                DatabaseContractIncome.IncomeEntry.COLUMN_TIMESTAMP,
                DatabaseContractIncome.IncomeEntry.COLUMN_CATEGORY
        };

        Cursor cursor = db.query(
                DatabaseContractIncome.IncomeEntry.TABLE_NAME,
                projection,
                null,
                null,
                null,
                null,
                null
        );

        StringBuilder records = new StringBuilder();
        while (cursor.moveToNext()) {
            String income = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContractIncome.IncomeEntry.COLUMN_INCOME));
            String timestamp = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContractIncome.IncomeEntry.COLUMN_TIMESTAMP));
            String category = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContractIncome.IncomeEntry.COLUMN_CATEGORY));

            records.append("收入来源：").append(category).append("\n");
            records.append("金额：").append(income).append(" 时间戳：").append(timestamp).append("\n");
        }

        cursor.close();
        db.close();

        tvRecords.setText(records.toString());
    }

    private void clearRecords() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        db.delete(DatabaseContractIncome.IncomeEntry.TABLE_NAME, null, null);
        db.close();
        tvRecords.setText("");
    }
}